package com.github.zdg.recyclerview.itemdecoration;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

public class LinearEdgeDividerDecoration extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };
    public static final int HORIZONTAL = 0;
    public static final int VERTICAL = 1;
    private Drawable mDivider;
    private int mOrientation;
    private final Rect mBounds = new Rect();
    private Edge mEdge = new Edge(Edge.BUTTOM_EDGE);
    public LinearEdgeDividerDecoration(Context context, int orientation) {
       this(context,orientation,null);
    }
    public LinearEdgeDividerDecoration(Context context, int orientation, Drawable divider) {
        if (divider == null) {
            TypedArray a = context.obtainStyledAttributes(ATTRS);
            this.mDivider = a.getDrawable(0);
            a.recycle();
        } else {
            this.mDivider=divider;
        }

        this.setOrientation(orientation);
    }
    public void setOrientation(int orientation) {
        if(orientation != 0 && orientation != 1) {
            throw new IllegalArgumentException("Invalid   It should be either HORIZONTAL or VERTICAL");
        } else {
            this.mOrientation = orientation;
        }
    }

    public void setDrawable(@NonNull Drawable drawable) {
        if(drawable == null) {
            throw new IllegalArgumentException("Drawable cannot be null.");
        } else {
            this.mDivider = drawable;
        }
    }

    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if(parent.getLayoutManager() != null) {
            if(this.mOrientation == 1) {
                this.drawVertical(c, parent);
            } else {
                this.drawHorizontal(c, parent);
            }

        }
    }

    @SuppressLint({"NewApi"})
    private void drawVertical(Canvas canvas, RecyclerView parent) {
        canvas.save();
        int left;
        int right;
        if(parent.getClipToPadding()) {
            left = parent.getPaddingLeft();
            right = parent.getWidth() - parent.getPaddingRight();
            canvas.clipRect(left, parent.getPaddingTop(), right, parent.getHeight() - parent.getPaddingBottom());
        } else {
            left = 0;
            right = parent.getWidth();
        }

        int childCount = parent.getChildCount();
        int itemCount = parent.getAdapter().getItemCount();
        for(int i = 0; i < childCount; ++i) {
            View child = parent.getChildAt(i);
            final int adapterPosition = parent.getChildAdapterPosition(child);
            parent.getDecoratedBoundsWithMargins(child, this.mBounds);
            int bottom = this.mBounds.bottom + Math.round(ViewCompat.getTranslationY(child));
            int top = bottom - this.mDivider.getIntrinsicHeight();
            if (isFirstRow(adapterPosition) && mEdge.isShowEdge(Edge.TOP_EDGE)) {
                this.mDivider.setBounds(left, this.mBounds.top, right, this.mBounds.top+this.mDivider.getIntrinsicHeight());
                this.mDivider.draw(canvas);
            }
            if (isLastRow(adapterPosition, itemCount) && i == childCount - 1 && !mEdge.isShowEdge(Edge.BUTTOM_EDGE)) {
                top=bottom=0;
            }
            this.mDivider.setBounds(left, top, right, bottom);
            this.mDivider.draw(canvas);
        }

        canvas.restore();
    }

    @SuppressLint({"NewApi"})
    private void drawHorizontal(Canvas canvas, RecyclerView parent) {
        canvas.save();
        int top;
        int bottom;
        if(parent.getClipToPadding()) {
            top = parent.getPaddingTop();
            bottom = parent.getHeight() - parent.getPaddingBottom();
            canvas.clipRect(parent.getPaddingLeft(), top, parent.getWidth() - parent.getPaddingRight(), bottom);
        } else {
            top = 0;
            bottom = parent.getHeight();
        }


        int itemCount = parent.getAdapter().getItemCount();
        int childCount = parent.getChildCount();
        for(int i = 0; i < childCount; ++i) {
            View child = parent.getChildAt(i);
            final int adapterPosition = parent.getChildAdapterPosition(child);
            parent.getLayoutManager().getDecoratedBoundsWithMargins(child, this.mBounds);
            if (isFirstColumn(adapterPosition)&&i==0&& mEdge.isShowEdge(Edge.LEFT_EDGE)) {
                this.mDivider.setBounds(0, top, this.mDivider.getIntrinsicWidth(), bottom);
                this.mDivider.draw(canvas);
                Log.e("zoudong", "isFirstColumn");
            }
            Log.e("zoudong", "this.mBounds=" + this.mBounds.toShortString());
            int right = this.mBounds.right + Math.round(ViewCompat.getTranslationX(child));
            int left = right - this.mDivider.getIntrinsicWidth();

            if (isLastColumn(adapterPosition, itemCount) && i == childCount - 1 && !mEdge.isShowEdge(Edge.RIGHT_EDGE)) {
                left=right=0;
            }

            this.mDivider.setBounds(left, top, right, bottom);
            this.mDivider.draw(canvas);
        }

        canvas.restore();
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        final int adapterPosition = parent.getChildAdapterPosition(view);
        final int itemCount = parent.getAdapter().getItemCount();
        if(this.mOrientation == VERTICAL) {
            outRect.right=outRect.left=0;
            if (isFirstRow(adapterPosition)&&mEdge.isShowEdge(Edge.TOP_EDGE)) { //第一个且需要左边距
                outRect.top=this.mDivider.getIntrinsicHeight();
            }
            outRect.bottom =this.mDivider.getIntrinsicHeight();
            if (isLastRow(adapterPosition,itemCount)&&!mEdge.isShowEdge(Edge.BUTTOM_EDGE)) {
                outRect.bottom=0;
            }
        } else {
            outRect.top = outRect.bottom = 0;
            if (isFirstColumn(adapterPosition)&&mEdge.isShowEdge(Edge.LEFT_EDGE)) { //第一个且需要左边距
                outRect.left=this.mDivider.getIntrinsicWidth();
            }
            outRect.right =this.mDivider.getIntrinsicWidth();
            if (isLastColumn(adapterPosition,itemCount)&&!mEdge.isShowEdge(Edge.RIGHT_EDGE)) {
                outRect.right=0;
            }
        }
    }

    private boolean isFirstColumn(int position) {
        if (mOrientation ==  VERTICAL) {
            return true;
        } else {
            return position==0;
        }
    }

    private boolean isLastColumn(int position, int childCount) {
        if (mOrientation ==  VERTICAL) {
            return true;
        } else {
            return position==childCount-1;
        }
    }

    private boolean isFirstRow(int position) {
        if (mOrientation ==  VERTICAL) {
            return position==0;
        } else {
            return true;
        }
    }

    private boolean isLastRow(int position,int childCount) {
        if (mOrientation ==  VERTICAL) {
            return position==childCount-1;
        } else {
            return true;
        }
    }

    public void setEdge(Edge edge) {
        this.mEdge = edge;
    }

    public Edge getEdge() {
        return mEdge;
    }
}